package com.turtle3d.util;

import java.util.Enumeration;

import javax.media.j3d.BranchGroup;
import javax.media.j3d.Transform3D;
import javax.media.j3d.TransformGroup;
import javax.vecmath.Point3f;

/**
 * Class used for cropping 3d image. Holds extremal positions in each axis.  
 * 
 * @author Marek Paterczyk <marek.paterczyk@gmail.com>
 *
 */
public class BranchBounds {

	private ExtremalValue posX = new ExtremalValue();

	private ExtremalValue posY = new ExtremalValue();

	private ExtremalValue posZ = new ExtremalValue();
	
	private Transform3D transform3D;

	public BranchBounds(BranchGroup fractalBranchGroup,
			TransformGroup rootTransformGroup) {

		// Viewport transform
		transform3D = new Transform3D();
		rootTransformGroup.getTransform(transform3D);

		// Iterate scene TransformGroups
		Enumeration children = fractalBranchGroup.getAllChildren();

		while (children.hasMoreElements()) {
			Object o = children.nextElement();
			TransformGroup tg = ((TransformGroup) o);
			Transform3D objTransform3D = new Transform3D();
			tg.getTransform(objTransform3D);

			//transform3D.mul(objTransform3D);
			//objTransform3D.mul(transform3D);
			
			Point3f point = new Point3f(0, 0, 0);
			objTransform3D.transform(point);
			//transform3D.transform(point);

			posX.setValue(point.x);
			posY.setValue(point.y);
			posZ.setValue(point.z);

		}

	}

	public ExtremalValue getPosX() {
		return posX;
	}

	public ExtremalValue getPosY() {
		return posY;
	}

	public Point3f getMiddlePoint() {
		Point3f middle = new Point3f(posX.getMiddleValue(), posY.getMiddleValue(), posZ
				.getMiddleValue());
		
		//transform3D.transform(middle);
		
		return middle;
	}

	public float calculateDistance(float fov) {

		float x = posX.getDifferenceValue();
		float y = posY.getDifferenceValue();
		float z = posZ.getDifferenceValue();
		
		float h;
		if (x >= y && x >= z)
			h = x;
		else if(y >= x && y >= z)
			h = y;
		else
			h = z;

		return h / (2f * (float) Math.tan(fov / 2.));

	}

}
